<template>
  <el-dialog :close-on-click-modal="false"  ref="dialogform" :title="addEditName + title" :visible.sync="dialogVisible" width="50%"
    :before-close="handleClose">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
      <el-form-item label="转出设施名称" prop="sourceFacilityId">
        <el-select class="w100p" v-model="ruleForm.sourceFacilityId" clearable filterable placeholder="请选择设施名称" @change="(e) => {
    handleChangeFacility(e, 'sourceFacilityName')
  }">
          <el-option :disabled="ruleForm.targetFacilityId == item.facilityId" v-for="(item, index) in facilityList"
            :key="index" :label="item.facilityName" :value="item.facilityId" />
        </el-select>
      </el-form-item>
      <el-form-item label="转出批次名称" prop="sourceBatchId">
        <el-select v-model="ruleForm.sourceBatchId" class="w100p" clearable filterable placeholder="请选择批次" @change="(e) => {
    handleChangeBatch(e, 'sourceBatchName')
  }">
          <el-option :disabled="ruleForm.targetBatchId == item.batchId"
            v-if="ruleForm.sourceFacilityId == item.facilityId && item.status !== 'CREATE' && item.status !== 'COMPLETED'"
            v-for="(item, index) in batchList" :key="index" :value="item.batchId" :label="item.batchName" />
        </el-select>
        <span class="errText" v-show="addEditFlag == 'edit'">您当前可编辑</span>
        <span class="errText">{{ batchInfoMsg }}</span>
      </el-form-item>
      <el-form-item label="转入设施名称" prop="targetFacilityId">
        <el-select class="w100p" v-model="ruleForm.targetFacilityId" clearable filterable placeholder="请选择设施名称" @change="(e) => {
    handleChangeFacility(e, 'targetFacilityName')
  }">
          <el-option :disabled="ruleForm.sourceFacilityId == item.facilityId" v-for="(item, index) in facilityList"
            :key="index" :label="item.facilityName" :value="item.facilityId" />
        </el-select>
      </el-form-item>
      <el-form-item label="转入批次名称" prop="targetBatchId">
        <el-select v-model="ruleForm.targetBatchId" class="w100p" clearable filterable placeholder="请选择批次" @change="(e) => {
    handleChangeBatch(e, 'targetBatchName')
  }">
          <el-option :disabled="ruleForm.sourceBatchId == item.batchId"
            v-if="ruleForm.targetFacilityId == item.facilityId && item.status !== 'COMPLETED'"
            v-for="(item, index) in batchList" :key="index" :value="item.batchId" :label="item.batchName" />
        </el-select>
      </el-form-item>
      <el-row v-for="item, index in ruleForm.transferDetailList" :key="index">
        <el-col :span="12">
          <el-form-item :label="index == 0 ? '转入类型' : ''" :prop="`transferDetailList[${index}][fishType]`"
            :rules="rules.fishType">
            <el-select v-model="item.fishType" class="w100p" clearable filterable placeholder="请选择类型"
              @change="handleChngeFishType">
              <el-option label="活鱼" value="LIVE_FISH"></el-option>
              <el-option label="次鱼" value="SECONDARY_FISH"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="index == 0 ? '转入品种' : ''" :prop="`transferDetailList[${index}][plantVarietyId]`"
            :rules="rules.plantVarietyId">
            <el-select v-model="item.plantVarietyId" class="w100p" clearable filterable placeholder="请选择品种" @change="(e) => {
    handleChangeVariety(e, index)
  }">
              <el-option v-if="plantVarietyIdList.includes(item.plantVarietyId)" v-for="item, index in varietyList"
                :disabled="choosePlantVarietyIdList.includes(item.plantVarietyId)" :key="index"
                :label="item.plantVarietyName" :value="item.plantVarietyId"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="index == 0 ? '转入规格' : ''" :prop="`transferDetailList[${index}][specificationId]`"
            :rules="rules.specificationId">
            <el-select v-model="item.specificationId" class="w100p" clearable filterable placeholder="请选择规格">
              <el-option v-if="s.plantVarietyId == item.plantVarietyId" v-for="s, index in specificationList"
                :key="index" :label="s.specificationName" :value="s.specificationId"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="index == 0 ? '转入数量(粒)' : ''" :prop="`transferDetailList[${index}][num]`"
            :rules="rules.num">
            <el-input type="number" v-model="item.num" placeholder="请输入参数"
              @change="handlePondInfo(index, item.plantVarietyId, item.num)"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="index == 0 ? '转入重量(斤)' : ''" :prop="`transferDetailList[${index}][weight]`"
            :rules="rules.weight">
            <el-input type="number" v-model="item.weight" placeholder="请输入参数"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="2">
          <i class="icon el-icon-circle-plus-outline" @click.stop="addMaterial()"></i>
          <i v-show="index" class="icon el-icon-remove-outline" @click.stop="delMaterial(index)"></i>
        </el-col>
      </el-row>
      <el-form-item label="转塘人" prop="staffId">
        <el-select v-model="ruleForm.staffId" class="w100p" placeholder="请选择操作人" @change="handleChangePerson">
          <el-option v-for="item, index in person" :key="index" :label="item.person.name"
            :value="item.person.personNo"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="转塘日期" prop="recordDate">
        <el-date-picker v-model="ruleForm.recordDate" value-format="yyyy-MM-dd" align="right" type="date"
          placeholder="选择日期" :picker-options="pickerOptions">
        </el-date-picker>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="submitForm">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>

import batch from '@/api/batch/batchManagement';
import transferPondRecords from '@/api/transferPondManagment/transferPondRecords.js';
export default {
  components: {},
  props: {
    addEditFlag: {
      type: String,
      default: () => {
        return 'add'
      }
    },
    data: {
      type: Object,
      default: () => {
        return {}
      }
    },
    title: {
      type: String,
      default: () => {
        return '操作表单'
      }
    },
    dialogVisible: {
      type: Boolean,
      default: () => {
        return false
      }
    },
    varietyList: {
      type: Array,
      default: () => {
        return []
      }
    },
    facilityList: {
      type: Array,
      default: () => {
        return []
      }
    },
    batchList: {
      type: Array,
      default: () => {
        return []
      }
    },
    specificationList: {
      type: Array,
      default: () => {
        return []
      }
    }
  },

  computed: {
    fishType () {
      return this.$store.state.initData.enum.fishType
    },
    person () {
      return this.$store.state.initData.person || [];
    },
  },
  data () {
    let validatorNumber_integer = function (rule, value, callback) {
      if (value > 0 && value % 1 == 0)
      {
        callback()
      } else
      {
        callback(new Error('请输入大于0的数值！'))
      }
    }
    let validatorNumber_weight = function (rule, value, callback) {
      if (value > 0)
      {
        callback()
      } else
      {
        callback(new Error('请输入大于0的数值！'))
      }
    }
    return {
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() > Date.now();
        },
        shortcuts: [{
          text: '今天',
          onClick (picker) {
            picker.$emit('pick', new Date());
          }
        }, {
          text: '昨天',
          onClick (picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24);
            picker.$emit('pick', date);
          }
        }, {
          text: '一周前',
          onClick (picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', date);
          }
        }]
      },
      addEditName: '添加',
      addEditApi: '',
      ruleForm: {},
      rules: {
        sourceFacilityId: [
          { required: true, message: '请选择养殖设施', trigger: 'change' }
        ],
        sourceBatchId: [
          { required: true, message: '请选择批次', trigger: 'change' }
        ],
        targetFacilityId: [
          { required: true, message: '请选择养殖设施', trigger: 'change' }
        ],
        targetBatchId: [
          { required: true, message: '请选择批次', trigger: 'change' }
        ],
        transferDetailList: [
          { required: true, message: '请选择批次', trigger: 'change' }
        ],
        staffId: [
          { required: true, message: '请选择操作人', trigger: 'change' }
        ],
        recordDate: [
          { required: true, message: '请选择转塘日期', trigger: 'change' }
        ],
        specificationId: [
          { required: true, message: '请选择规格', trigger: 'change' }
        ],
        plantVarietyId: [
          { required: true, message: '请选择品种', trigger: 'change' }
        ],
        fishType: [
          { required: true, message: '请选择类型', trigger: 'change' }
        ],
        num: [
          { required: true, validator: validatorNumber_integer, trigger: 'change' }
        ],
        weight: [
          { required: true, validator: validatorNumber_weight, trigger: 'change' }
        ],
        
      },
      batchInfoMsg: '',
      batchInfo: {},
      plantVarietyIdList: [],
      choosePlantVarietyIdList: []
    }
  },
  watch: {
    dialogVisible (v) {
      v && this.initData()
    }
  },

  mounted () { },
  methods: {
    initData () {
      if (this.addEditFlag == 'add')
      {
        this.resetForm()
        if (this.ruleForm.transferDetailList && Array.isArray(this.ruleForm.transferDetailList))
        {
          this.$set(this.ruleForm.transferDetailList, 0, {
            specificationId: null, plantVarietyId: null, num: null, weight: null
          })
        } else
        {
          this.$set(this.ruleForm, 'transferDetailList', [{
            specificationId: null, plantVarietyId: null, num: null, weight: null
          }])
        }
        this.addEditApi = transferPondRecords.add
        this.addEditName = '添加'
        this.batchInfoMsg = ''
        this.batchInfo = {}
        this.plantVarietyIdList = []
        this.choosePlantVarietyIdList = []
      } else if (this.addEditFlag == 'edit')
      {
        this.ruleForm = {
          ...this.data,
          staffId: this.data.personNo || this.data.staffId,
        }
        this.addEditApi = transferPondRecords.edit
        this.addEditName = '编辑';
        this.choosePlantVarietyIdList = []
        this.ruleForm.transferDetailList.forEach(item => {
          this.choosePlantVarietyIdList.push(item.plantVarietyId)
        })
        this.queryByConditionPondInfo(this.data.sourceBatchId)
      }
    },
    handleChangeVariety (e, index) {
      this.choosePlantVarietyIdList = []
      this.$set(this.ruleForm.transferDetailList[index], 'specificationId', '')
      this.ruleForm.transferDetailList.forEach(item => {
        this.choosePlantVarietyIdList.push(item.plantVarietyId)
      })
    },
    handleChngeFishType (type) {
      for (let key in this.fishType)
      {
        if (key == type)
        {
          this.$set(this.ruleForm, 'fishTypeName', this.fishType[key]);
        }
      }
    },
    handleChangePerson (id) {
      let row = this.person.find(item => Number(item.person.personNo) == id);
      this.$set(this.ruleForm, 'staffName', row.person.name);
    },
    handleChangeFacility (e, key) {
      let row = this.facilityList.find(item => Number(item['facilityId']) == Number(e));
      this.$set(this.ruleForm, key, row['facilityName'] || '');
      if (key == 'sourceFacilityName')
      {
        this.$set(this.ruleForm, 'sourceBatchId', '');
        this.$set(this.ruleForm, 'sourceBatchName', '');
      } else if (key == 'targetFacilityName')
      {
        this.$set(this.ruleForm, 'targetBatchId', '');
        this.$set(this.ruleForm, 'targetBatchName', '');
      }
    },
    handlePondInfo (index, plantVarietyId, num) {
      console.log(index, plantVarietyId, num)
      let maxNum = this.batchInfo[plantVarietyId] || 0
      if (plantVarietyId)
      {
        if (num > maxNum)
        {
          this.$message.warning('该品种转入粒数不得超出在塘数量');
          this.ruleForm.transferDetailList[index].num = 0;
        }
      }
    },
    handleChangeBatch (e, key) {
      let row = this.batchList.find(item => Number(item['batchId']) == Number(e));
      this.$set(this.ruleForm, key, row['batchName'] || '');
      if (key == 'sourceBatchName')
      {
        this.queryByConditionPondInfo(e)
      }
    },
    async queryByConditionPondInfo (id) {
      this.plantVarietyIdList = [];
      this.batchInfoMsg = '';
      this.batchInfo = {};
      if (!id) return;
      try
      {
        const res = await batch.queryAllByBatchId(id);
        // 检查返回的状态码  
        if (res.code !== 1 && !res.data)
        {
          return; // 如果状态码不是1，直接返回并不做后续处理  
        }
        let batchInfoList = res.data || [];
        if (batchInfoList.length > 0)
        {
          batchInfoList.forEach((item, index) => {
            this.plantVarietyIdList.push(item.plantVarietyId);
            this.batchInfoMsg += `${item.plantVarietyName}在塘数为${item.num + this.getInputPondNum(item.plantVarietyId)}粒${index + 1 == batchInfoList.length ? '!' : ';'}`
            this.batchInfo[item.plantVarietyId] = item.num + this.getInputPondNum(item.plantVarietyId);
          })
        } else
        {
          this.plantVarietyIdList = []
          this.$message.warning('请重新选择批次，该批次养殖数据！')
        }
      } catch (error)
      {
        console.log(error);
      }
    },
    getInputPondNum (plantVarietyId) {
      let row = this.ruleForm.transferDetailList.find(item => { return item.plantVarietyId == plantVarietyId });
      return row && row.num ? row.num : 0
    },
    addMaterial () {
      let length = this.ruleForm.transferDetailList?.length || 0
      if (length)
      {
        this.$set(this.ruleForm.transferDetailList, length, {
          specificationId: null, plantVarietyId: null, num: null, weight: null
        })
      }
    },
    delMaterial (index) {
      let list = this.ruleForm.transferDetailList;
      list.splice(index, 1);
      this.$set(this.ruleForm, 'transferDetailList', list)
    },
    //提交表单
    submitForm () {
      this.$refs.ruleForm.validate((valid) => {
        if (valid)
        {
          this.ruleForm.transferDetailList.forEach(item => {
            let specificationObj = this.specificationList.find(s => Number(s['specificationId']) == item.specificationId);
            let plantVarietyObj = this.varietyList.find(s => Number(s['plantVarietyId']) == item.plantVarietyId);
            item.specificationName = specificationObj.specificationName;
            item.plantVarietyName = plantVarietyObj.plantVarietyName;
          })
          this.addEditApi({ ...this.ruleForm }).then(res => {
            if (res.code == 1)
            {
              this.cancel();
              this.$message.success('添加成功')
            } else
            {
              this.$message.warning(res.msg || '添加失败')
            }
          }).catch(err => {
            console.log(err)
          })
        } else
        {
          return false;
        }
      })
    },
    //重置
    resetForm () {
      this.ruleForm = {};
      this.$refs.ruleForm && this.$refs.ruleForm.resetFields()
    },
    //取消关闭
    cancel () {
      this.resetForm()
      this.$emit("closeDialog")
    },
    handleClose (done) {
      this.$confirm('确认关闭？')
        .then(_ => { this.resetForm(); this.cancel() })
        .catch(_ => { });
    }
  }
};
</script>
<style lang="scss" scoped>
.line {
  border-bottom: 1px solid #e6e6e6;
}

.icon {
  font-size: 20px;
  line-height: 29px;
  cursor: pointer;
}

::v-deep .noLabel {
  .el-form-item {
    .label {
      display: none;
    }

    .el-form-item__content {
      margin: 0;
    }
  }
}
</style>